<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery1">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="门店">
              <a-cascader :options="departModel.departTreeOptions" :showSearch="true" expand-trigger="hover"
                placeholder="" :fieldNames="departModel.fieldNames" style="width: 180px"
                v-model="queryParam.selecteddeparts" />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="手机号">
              <a-input v-model="queryParam.mobile" allowClear></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="会员状态">
              <a-select v-model="queryParam.bizStatus" allowClear>
                <a-select-option value="1"> 启用 </a-select-option>
                <a-select-option value="0"> 禁用 </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="生日筛选">
              <a-select v-model="queryParam.birthTag" allowClear>
                <a-select-option value="TODAY"> 今天 </a-select-option>
                <a-select-option value="TOMORROW"> 明天 </a-select-option>
                <a-select-option value="DAYS_7"> 近7天 </a-select-option>
                <a-select-option value="DAYS_30"> 近30天 </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery1" icon="search">查询</a-button>
              <a-button type="default" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '高级查询' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="5" :lg="7" :md="8" :sm="24">
            <a-form-item label="注册时间">
              <a-range-picker
                :ranges="{ 今天: [moment(), moment()], 近7天:[moment().subtract(7, 'days'),moment()],本月: [moment().startOf('month'), moment().endOf('month')] }"
                v-model="orderDateRange"
                @change="handleChange"
              />
            </a-form-item>
          </a-col>
            <a-col :xl="5" :lg="7" :md="8" :sm="24">
              <a-form-item>
                <a-checkbox v-model="queryParam.hasPoints">是否有积分</a-checkbox>
                  <a-input-number min=0 v-model="queryParam.startPoints" :formatter="limitNumber" :parser="limitNumber" :disabled="!queryParam.hasPoints"/>
                  -
                  <a-input-number min=0 v-model="queryParam.endPoints" :formatter="limitNumber" :parser="limitNumber" :disabled="!queryParam.hasPoints"/>
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="7" :md="8" :sm="24">
              <a-form-item>
                消费次数
                  <a-input-number min=0 v-model="queryParam.startOrderCnt" :formatter="limitNumber" :parser="limitNumber" />
                  -
                  <a-input-number min=0 v-model="queryParam.endOrderCnt" :formatter="limitNumber" :parser="limitNumber" />
              </a-form-item>
            </a-col>
            <a-col :xl="5" :lg="7" :md="8" :sm="24">
              <a-form-item >
                消费总金额（元）
                  <a-input-number min=0 v-model="queryParam.startOrderAmount" :formatter="limitNumber" :parser="limitNumber" />
                  -
                  <a-input-number min=0 v-model="queryParam.endOrderAmount" :formatter="limitNumber" :parser="limitNumber" />
              </a-form-item>
            </a-col>
          </template>
          
        </a-row>
      </a-form>
    </div>

    <a-divider style="margin-top:0px;"></a-divider>
    
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-dropdown>
        <a-menu slot="overlay" theme="dark">
          <a-menu-item key="M" @click="distCouponModal('M')">选择的会员</a-menu-item>
          <a-menu-item key="A" @click="distCouponModal('A')">选择全部查询结果</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px" type="primary"> 批量发券
          <a-icon type="down" />
        </a-button>
      </a-dropdown>
      <a-button type="default" icon="download" @click="handleExportXls1('会员信息')">导出会员</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <a-table ref="table" size="middle" bordered rowKey="id" :columns="columns" :dataSource="dataSource"
        :pagination="ipagination" :loading="loading" class="j-table-force-nowrap"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" @change="handleTableChange">
        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <span v-has="'posMember:disabled'">
            <a-divider type="vertical" />
            <a @click="handleStatus(record,0)" v-if="record.bizStatus == 1" style="color:#777">禁用</a>
            <a @click="handleStatus(record,1)" v-else style="color:#777">启用</a>
          </span>
        </span>
        <span slot="bizStatus" slot-scope="text">
          <a-tag v-if="text === 0">禁用</a-tag>
          <a-tag color="blue" v-else>启用</a-tag>
        </span>
        <span slot="logo" slot-scope="text">
          <a-avatar shape="square" :src="text"> </a-avatar>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->
    <j-modal title="修改会员状态" :width="500" :visible="visible" :confirmLoading="confirmLoading" destroyOnClose
      @ok="handleOk" @cancel="handleCancel" cancelText="关闭">
      <a-spin :spinning="confirmLoading">
        <a-form-model ref="form" :model="model">
          <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="disabledReason" label="禁用原因">
            <a-textarea :rows="4" placeholder="最多支持100个字" :maxlength="100" v-model="model.disabledReason" />
          </a-form-model-item>
        </a-form-model>
      </a-spin>
    </j-modal>
  </a-card>
</template>

<script>
import '@/assets/less/TableExpand.less'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { queryDepartTreeList1 } from '@/api/api'
import { limitNumber, isUnSignInt, isUnSignDig2 } from '@/utils/util'
import { postAction } from '@/api/manage'
import moment from 'moment'

export default {
  name: 'PosShopMemberList',
  mixins: [JeecgListMixin],
  components: {
  },
  data() {
    return {
      description: '会员管理页面',
      limitNumber,
      moment,
      distCouponModel: {
        ty: 'M',
        selectRows: [],
        queryParam: {},
      },
      model: {},
      departModel: {
        departTreeOptions: [],
        fieldNames: { label: 'title', value: 'value', children: 'children' },
      },
      orderDateRange: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      // 表头
      columns: [
        {
          title: '所属机构',
          align: 'center',
          dataIndex: 'orgName',
        },
        {
          title: '注册门店',
          align: 'center',
          dataIndex: 'shopName',
        },
        {
          title: '手机号',
          align: 'center',
          dataIndex: 'mobile',
        },
        {
          title: '头像',
          align: 'center',
          dataIndex: 'logo',
          scopedSlots: { customRender: 'logo' },
        },
        {
          title: '昵称/姓名',
          align: 'center',
          dataIndex: 'nickName',
        },
        {
          title: '注册时间',
          align: 'center',
          dataIndex: 'regTime',
        },
        // {
        //   title: '注册渠道',
        //   align: 'center',
        //   dataIndex: 'regSource',
        // },
        {
          title: '性别',
          align: 'center',
          dataIndex: 'sex',
        },
        {
          title: '生日',
          align: 'center',
          dataIndex: 'birth',
          sorter: true,
        },
        {
          title: '当前积分',
          align: 'center',
          dataIndex: 'pointsBalance',
          sorter: true,
        },
        {
          title: '可用优惠券（张）',
          align: 'center',
          dataIndex: 'canUseCoupon',
        },
        {
          title: '最近到店',
          align: 'center',
          dataIndex: 'recentConsumptionTime',
        },
        {
          title: '消费总次数',
          align: 'center',
          dataIndex: 'totalOrderCnt',
          sorter: true,
        },
        {
          title: '消费总金额（元）',
          align: 'center',
          dataIndex: 'totalOrderAmount',
          sorter: true,
        },
        {
          title: '状态',
          align: 'center',
          dataIndex: 'bizStatus',
          scopedSlots: { customRender: 'bizStatus' },
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          scopedSlots: { customRender: 'action' },
        },
      ],
      shopList: [],
      confirmLoading: false,
      visible: false,
      validatorRules: {
        disabledReason: [{ required: true, message: '必填项' }],
      },
      url: {
        list: '/member/posShopMember/list',
        changeStatus: '/member/posShopMember/changeStatus',
        exportXlsUrl: 'member/posShopMember/exportXls',
        shopListUrl: '/stock/posShop/shopList',
      },
    }
  },
  created() {
    this.loadDepartTree()
  },
  methods: {
    searchQuery1() {
      this.assembleQueryParam()
      this.loadData()
    },
    assembleQueryParam() {
      console.log(this.queryParam.selecteddeparts)
      let selecteddeparts = this.queryParam.selecteddeparts
      if (selecteddeparts && selecteddeparts.length == 2) {
        this.queryParam.orgIds = selecteddeparts[0]
        this.queryParam.shopIds = selecteddeparts[1] == 0 ? null : selecteddeparts[1]
      } else {
        this.queryParam.orgIds = null
        this.queryParam.shopIds = null
      }
    },
    checkExportParam() {
      // let orgIds = this.queryParam.orgIds
      // if(!orgIds || orgIds == '0'){
      //   this.$message.warning('请选择市场后进行导出操作')
      //   return false
      // }
      let total = this.ipagination.total
      if (total > 10000) {
        this.$message.warning('单次导出最多支持10000条')
        return false
      }
      return true
    },
    handleChange(date, dateString) {
      this.queryParam.beginTime = dateString[0]
      this.queryParam.endTime = dateString[1]
    },
    handleExportXls1(fileName) {
      if (!this.checkExportParam()) {
        return
      }
      this.handleExportXls(fileName)
    },
    handleStatus(record, bizStatus) {
      this.model.id = record.id
      this.model.bizStatus = bizStatus
      if (bizStatus == 1) {
        this.doChangeStatus()
      } else {
        this.model.disabledReason = ''
        this.visible = true
      }
    },
    handleOk() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.doChangeStatus()
        } else {
          return false
        }
      })
    },
    handleCancel() {
      this.visible = false
    },
    doChangeStatus() {
      let that = this
      let params = {
        id: that.model.id, 
        disabledReason: that.model.disabledReason,
        bizStatus: that.model.bizStatus
      }

      that.confirmLoading = true

      postAction(that.url.changeStatus, params)
        .then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.visible = false
            that.loadData(1)
          } else {
            that.$message.warning(res.message)
          }
        })
        .finally(() => {
          that.confirmLoading = false
        })
    },
    distCouponModal(ty) {
      console.log('this.selectionRows', this.selectionRows)
      if (ty === 'M') {
        if (this.selectionRows.length === 0) {
          this.$message.warning('请选择会员');
          return false
        } else {
          let selectRows = this.selectionRows
          let memberIds = new Array()
          for (var row of selectRows) {
            memberIds.push(row.id)
          }
          this.distCouponModel = {
            'ty': ty,
            'memberIds': memberIds.join(',')
          }
          
        }
      } else {
        let total = this.ipagination.total
        if (total == 0) {
          this.$message.warning('无可用会员')
          return false
        }
        if (total >= 10000) {
          this.$message.warning('单次发券会员数量不能超过10000条')
          return false
        }

        this.assembleQueryParam()

        let orgIds = this.queryParam.orgIds
        if (!orgIds) {
          this.$message.warning('请选择市场后进行操作')
          return false
        }

        this.distCouponModel = {
          'ty': ty,
          'queryParam': this.queryParam
        }
        console.log('===distCouponModel===', this.distCouponModel)
      }
      this.onClearSelected()
      this.$router.push({ name: 'DistCouponStepForm', params: this.distCouponModel })
    },
    loadDepartTree() {
      queryDepartTreeList1().then((res) => {
        if (res.success) {
          let departList = res.result
          if (departList.length == 1 && departList[0].orgType == 1) {
            departList = departList[0].children
          }
          this.departModel.departTreeOptions = departList

          this.departModel.departTreeOptions.forEach((x) => {
            if (!x['children']) {
              x['children'] = []
            }
            let allShop = { title: '全部门店', value: '0' }
            x['children'].unshift(allShop)
          })
        }
      })
    },
    handleDetail(record) {
      this.$router.push({ name: 'PosShopMemberModal', params: record })
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>